package com.roger.springcloudGreenwich.springsecurity.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.roger.springcloudGreenwich.springsecurity.domain.Permission;
import com.roger.springcloudGreenwich.springsecurity.domain.Users;
import com.roger.springcloudGreenwich.springsecurity.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

;import java.util.ArrayList;
import java.util.List;

/**
 * Created by yulei on 2022/10/7.
 */
@Service
public class MyUserDetailService implements UserDetailsService{
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //使用数据库
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username",username);

        Users users = usersMapper.selectOne(wrapper);

        if(users == null){
            return null;
        }

        //查询用户权限
        List<Permission> permissionList = usersMapper.findPermissionByUsername(username);

        //将自定义
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        for(Permission permission : permissionList){
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        }

        UserDetails userDetails = User.withUsername(users.getUsername())
                .password(users.getPassword())
                .authorities(grantedAuthorities)
                .build();

        return userDetails;
    }
}
